﻿#region File and License Information
/*
<File>
	<License>
		Copyright © 2009 - 2017, Daniel Vaughan. All rights reserved.
		This file is part of Calcium (http://calciumsdk.net), 
		which is released under the MIT License.
		See file /Documentation/License.txt for details.
	</License>
	<CreationDate>2012-02-18 13:39:57Z</CreationDate>
</File>
*/
#endregion

using System;
using System.Collections.Generic;

#if SILVERLIGHT
using System.Windows.Browser;
#endif

namespace Outcoder.Net
{
	public class HttpUtilityExtended
	{
		public static IDictionary<string, string> ParseQueryString(string queryString)
		{
#if WINDOWS_UWP || NETFX_CORE
			var parameterDictionary = new Dictionary<string, string>();
#else
			var parameterDictionary = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
#endif
			int startIndex = queryString.IndexOf('?');
			string queryPart;
			if (startIndex > -1)
			{
				queryPart = queryString.Substring(startIndex + 1);
			}
			else
			{
				queryPart = queryString;
			}

			string[] strings = queryPart.Split('&');

			foreach (string queryItem in strings)
			{
				int equalsIndex = queryItem.IndexOf('=');
				if (equalsIndex >= 0)
				{
					parameterDictionary[queryItem.Substring(0, equalsIndex)] = queryItem.Substring(equalsIndex + 1);
				}
				else
				{
					parameterDictionary[queryItem] = null;
				}
			}

			return parameterDictionary;
		}

		public static string HtmlEncode(string text)
		{
			string result;
#if WINDOWS_UWP || NETFX_CORE
			result = System.Net.WebUtility.HtmlEncode(text);
#elif WINDOWS_PHONE || __IOS__ || MONODROID
			result = System.Net.HttpUtility.HtmlEncode(text);
#else
			result = System.Web.HttpUtility.HtmlEncode(text);
#endif
			return result;
		}

		public static string HtmlDecode(string text)
		{
			string result;
#if WINDOWS_UWP || NETFX_CORE
			result = System.Net.WebUtility.HtmlDecode(text);
#elif WINDOWS_PHONE || __IOS__ || MONODROID
			result = System.Net.HttpUtility.HtmlDecode(text);
#else
			result = System.Web.HttpUtility.HtmlDecode(text);
#endif
			return result;
		}

		public static string UrlEncode(string text)
		{
#if WINDOWS_UWP || NETFX_CORE
			return System.Net.WebUtility.UrlEncode(text);
#elif WINDOWS_PHONE || __IOS__ || MONODROID
			return System.Net.HttpUtility.UrlEncode(text);
#else
			return System.Web.HttpUtility.UrlEncode(text);
#endif
		}

		public static string UrlDecode(string text)
		{
#if WINDOWS_UWP || NETFX_CORE
			return System.Net.WebUtility.UrlDecode(text);
#elif WINDOWS_PHONE || __IOS__ || MONODROID
			return System.Net.HttpUtility.UrlDecode(text);
#else
			return System.Web.HttpUtility.UrlDecode(text);
#endif
		}
	}
}
